from selenium import webdriver
import time
from PIL import Image
from io import BytesIO

from douban.YDMHTTPDemo import decode_image

# browser = webdriver.Chrome('‪C:\Python36\chromedriver')
browser = webdriver.Chrome()

browser.implicitly_wait(5)

browser.get("https://accounts.douban.com/login")

# 输入账号
browser.find_element_by_id("email").send_keys("18817482060")
# 输入密码
browser.find_element_by_id("password").send_keys("erhuo147")

# 输入验证码
try:
    img_code = browser.find_element_by_id("captcha_image")
    # 将出现的验证码截屏保存到文件
    png_data = browser.get_screenshot_as_png()
    # 对图片进行处理
    full_image = Image.open(BytesIO(png_data))
    full_image.save('full_image_code.png')
    # 得到全屏图片后，对对象进行截取
    # 获取图片验证码的位置
    left = img_code.location["x"]
    top = img_code.location["y"]
    width = img_code.size["width"]
    height = img_code.size["height"]
    right = left + width
    bottom = top + height
    # 截图
    cut_info = (left, top, right, bottom)
    cut_image = full_image.crop(cut_info)
    cut_image.save('rel_image_code.png')
    # 使用云打码识别图片验证码
    code = decode_image('rel_image_code.png')

    # 手动输入验证码
    # code = input('输入验证码：')
    browser.find_element_by_id("captcha_field").send_keys(code)
except:
    pass

browser.find_element_by_name("login").click()

time.sleep(15)

browser.quit()
